

#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>

int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        int cnt = 3;
        while(cnt)
        {
            sleep(3);
            printf("我是一个子进程，pid：%d，ppid：%d\n",getpid(),getppid());
            sleep(1);
            cnt--;
            //int* p = 0;
            //*p = 100;
            int a = 10;
            a /= 0;
        }
        exit(10);     //子进程退出
    }
    
    //父进程
    //1. 子进程退出
    //2. 子进程没有退出呢？？
    //pid_t rid = wait(NULL);
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)
    {
        if(WIFEXITED(status))
        {
            printf("wait success, rid: %d, exit code: %d, exit signal: %d\n", rid, WEXITSTATUS(status), status&0x7F);  //rid
        }
        //printf("wait success, rid: %d, exit code: %d, exit signal: %d\n", rid, (status>>8)&0xFF, status&0x7F);  //rid
        else 
        {
            printf("子进程异常！\n");
        }
    }
    else 
    {
        printf("wait error: %d: %s\n",errno,strerror(errno));
    }

    return 0;
}
